package com.itheima.health.common;

import com.itheima.health.dao.SetMealDao;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用于七牛云垃圾图片删除
 * @Created by PANG on 4/8/2022 上午9:50
 */
@Component
@Slf4j
public class DefiniteTimeGCPicConst {

    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private QiniuUtils qiniuUtils;

    private Set<String> trashSet = new HashSet<>();


    //不影响验证码的反序列化
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        this.redisTemplate = redisTemplate;
        this.redisTemplate.setKeySerializer(stringSerializer);
        this.redisTemplate.setValueSerializer(stringSerializer);
        this.redisTemplate.setHashKeySerializer(stringSerializer);
        this.redisTemplate.setHashValueSerializer(stringSerializer);
    }
    /**
     * 每日凌晨三点垃圾回收
     */
    @Scheduled(cron = "0 0 3 * * ? ")
    public void GCByDay(){
        log.info("垃圾图片回收..");
        trashSet = redisTemplate.opsForSet().members("trashPic");
        log.info("待回收集合为",trashSet.toArray());
        long currentTime =  System.currentTimeMillis();
        List<Setmeal> setmeals = setMealDao.selectListAll();
        cycle1:
        for (String filename : trashSet) {
            String[] strs =filename.split("_");
            long time = Long.valueOf(strs[0]);
            //判断上传时间是否在半小时内，是就不删(防止有人正在操作)
            if(currentTime-time<1800000){
                log.info("上传时间在半小时内{}",filename);
                continue cycle1;
            }
            //判断数据库里是否有该图片，是就不删,防止
            // 1.删除垃圾集合时网络波动的情况
            // 2.前一天删除时在半小时内没被删，之后提交到数据库的情况
            for (Setmeal setmeal : setmeals) {
                if(setmeal.getImg().equals(filename)){
                    //在缓存中删除该项
                    redisTemplate.opsForSet().remove("trashPic",filename);
                    log.info("该项在数据库中，删除缓存{}",filename);
                    continue cycle1;
                }
            }
            //如果仍未跳出本次循环，在云盘删除图片，在redis中删除该项
            qiniuUtils.deleteFileFromQiniu(filename);
            log.info("删除图片{}",filename);
            redisTemplate.opsForSet().remove("trashPic",filename);
            log.info("删除缓存{}",filename);
        }
    }
}
